#!/bin/bash
#!/bin/bash
chat_install() {
# 检查是否以root运行
if [ "$(id -u)" -ne 0 ]; then
    echo "错误: 需要root权限来写入/usr/bin/"
    echo "请使用sudo运行此脚本"
    exit 1
fi

# 使用cat和EOF写入脚本内容
cat > /usr/bin/chatgpt << 'EOF'
#!/bin/bash

# OpenAI API 交互式对话脚本
API_KEY="sk-pZe7jC3hANS2ldkrE4ZuadRHA9FIXSs6GeqS7RebPTqMYVhJ"
API_URL="https://sg.uiuiapi.com/v1/chat/completions"
MODEL="gpt-${1:-"4o"}"
HISTORY_FILE="/tmp/openai_chat_history_$(date +%s).json"

# 初始化对话历史
echo '[]' > "$HISTORY_FILE"

# 检查依赖
check_dependencies() {
    if ! command -v curl &> /dev/null; then
        apt install curl -y
        exit 1
    fi
    
    if ! command -v jq &> /dev/null; then
        apt install jq -y
        exit 1
    fi
}

# 发送消息到API
send_message() {
    local message="$1"
    
    # 添加用户消息到历史
    jq --arg role "user" --arg content "$message" \
       '. += [{"role": $role, "content": $content}]' \
       "$HISTORY_FILE" > "${HISTORY_FILE}.tmp" && mv "${HISTORY_FILE}.tmp" "$HISTORY_FILE"
    
    # 准备请求数据
    local request_data=$(jq -n --arg model "$MODEL" --slurpfile messages "$HISTORY_FILE" \
       '{"model": $model, "messages": $messages[0], "temperature": 0.7}')
    
    # 发送请求
    local response=$(curl -s -X POST "$API_URL" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $API_KEY" \
        -d "$request_data")
    
    # 提取助手回复
    local assistant_reply=$(echo "$response" | jq -r '.choices[0].message.content')
    
    # 添加助手回复到历史
    jq --arg role "assistant" --arg content "$assistant_reply" \
       '. += [{"role": $role, "content": $content}]' \
       "$HISTORY_FILE" > "${HISTORY_FILE}.tmp" && mv "${HISTORY_FILE}.tmp" "$HISTORY_FILE"
    
    echo -e "\nAI: $assistant_reply\n"
}

# 主循环
main() {
    check_dependencies
    
    echo -e "\n欢迎使用 $MODEL 交互式对话 (输入 'exit' 或 'quit' 退出)\n"
    
    while true; do
        read -p "你: " user_input
        
        # 检查退出条件
        if [[ "$user_input" == "exit" || "$user_input" == "quit" ]]; then
            echo "对话结束。"
            rm "$HISTORY_FILE"
            break
        fi
        
        # 检查空输入
        if [[ -z "$user_input" ]]; then
            echo "请输入有效内容或输入 'exit' 退出"
            continue
        fi
        
        send_message "$user_input"
    done
}

# 启动脚本
main
EOF

# 设置可执行权限
chmod +x /usr/bin/chatgpt

}
backup() {
    sudo apt update
    sudo apt-get install xz-utils -y
    #=== 配置 ===
    local BACKUP_DIR="${BACKUP_DIR:-$HOME/backups}"
    local LOG_FILE="$BACKUP_DIR/backup.log"
    local AUTO_RESTORE_CONF="$BACKUP_DIR/auto_restore.cfg"
    local DATE=$(date +%Y%m%d-%H%M%S)
    
    # 排除项 (系统+代码)
    local EXCLUDE=(
        "--exclude=$BACKUP_DIR"
        "--exclude=./backup.tar.xz"
    )

    #=== 核心函数 ===
    init_backup() {
        mkdir -p "$BACKUP_DIR"
        [ ! -f "$LOG_FILE" ] && touch "$LOG_FILE"
        echo "[$(date '+%F %T')] 操作: $1" >> "$LOG_FILE"
    }

    log() {
        echo "[$(date '+%F %T')] $1" >> "$LOG_FILE"
    }

    # 备份功能
    create_backup() {
        local target="$1"
        local output="$BACKUP_DIR/${2:-backup-$DATE.tar.xz}"
        
        echo "▶ 正在备份到: $output"
        echo "⏳ 这可能需要较长时间..."
        
        if sudo tar -cvpJf "$output" "${EXCLUDE[@]}" --one-file-system "$target" 2>> "$LOG_FILE"; then
            echo "✅ 备份成功! (大小: $(du -h "$output" | cut -f1))"
            log "创建备份: $output"
        else
            echo "❌ 备份失败! 查看日志: $LOG_FILE"
            return 1
        fi
    }

    # 还原功能
    restore_backup() {
        local file="$1"
        
        if [ ! -f "$file" ]; then
            echo "❌ 备份文件不存在: $file"
            return 1
        fi
        
        echo "⚠️ 警告: 即将还原系统! 输入 yes 确认: "
        read -r confirm
        if [ "$confirm" != "yes" ]; then
            echo "己取消还原操作"
            return
        fi
        
        echo "▶ 正在从 $file 还原..."
        if sudo tar -xvpJf "$file" -C / --numeric-owner 2>> "$LOG_FILE"; then
            echo "✅ 还原完成! 建议重启系统"
            log "系统已还原: $file"
        else
            echo "❌ 还原失败! 查看日志: $LOG_FILE"
        fi
    }

    # 自动还原管理
    auto_restore() {
        case $1 in
            on)
                if [ ! -f "$AUTO_RESTORE_CONF" ]; then
                    echo "❌ 未设置自动还原备份路径!"
                    return 1
                fi
                local backup_path=$(cat "$AUTO_RESTORE_CONF")
                
                cat <<EOF | sudo tee /etc/systemd/system/auto-restore.service >/dev/null
[Unit]
Description=Auto Restore System Backup
After=network.target

[Service]
ExecStart=/bin/tar -xJf "$backup_path" -C / --numeric-owner
Type=oneshot
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF
                sudo systemctl enable auto-restore.service
                echo "✅ 已启用开机自动还原"
                log "启用自动还原: $backup_path"
                ;;
            off)
                sudo systemctl disable --now auto-restore.service
                echo "✅ 已禁用自动还原"
                log "禁用自动还原"
                ;;
            set)
                echo "$2" > "$AUTO_RESTORE_CONF"
                echo "✅ 已设置自动还原路径: $2"
                log "设置自动还原路径: $2"
                ;;
            *)
                echo "用法: auto_restore [on|off|set <path>]"
                ;;
        esac
    }

    #=== 主菜单 ===
    while true; do
        clear
        echo "====== 智能备份还原工具 ======"
        echo "1. 完整系统备份 (需root)"
        echo "2. 指定目录备份"
        echo "3. 从备份还原系统 (需root)"
        echo "4. 自动还原管理"
        echo "5. 按默认配置备份"
        echo "6. 按默认配置还原"
        echo "7. 查看备份日志"
        echo "8. 退出"
        read -p "请选择: " choice

        case $choice in
            1)
                init_backup "全系统备份"
                create_backup "/" "full-system-$DATE.tar.xz"
                ;;
            2)
                read -p "输入要备份的目录路径: " target
                if [ -d "$target" ]; then
                    init_backup "目录备份: $target"
                    create_backup "$target" "dir-$(basename "$target")-$DATE.tar.xz"
                else
                    echo "❌ 目录不存在!"
                fi
                ;;
            3)
                read -p "输入备份文件路径: " file
                init_backup "系统还原"
                restore_backup "$file"
                ;;
            4)
                echo "1. 启用自动还原"
                echo "2. 禁用自动还原"
                echo "3. 设置自动还原路径"
                read -p "选择: " sub_choice
                case $sub_choice in
                    1) auto_restore on ;;
                    2) auto_restore off ;;
                    3)
                        read -p "输入备份文件路径: " path
                        auto_restore set "$path"
                        ;;
                esac
                ;;
            5)
                sudo tar -cvpJf backup.tar.xz \
                --exclude=./backup.tar.xz \
                --one-file-system /
                ;;
            6)
                sudo tar -xJvf ./backup.tar.xz -C / --no-same-owner --no-same-permissions
                ;;
            7)
                echo "=== 最近日志 ==="
                tail -n 10 "$LOG_FILE"
                ;;
            8)
                exit 0
                ;;
            *)
                echo "无效选项!"
                ;;
        esac
        read -p "按回车继续..."
    done
}

system_info() {
    echo "系统信息报告 - $(date)"
    echo "======================================"
    # 基本系统信息
    echo "主机名: $(hostname)"
    if [ -f /etc/os-release ]; then
        source /etc/os-release
        echo "操作系统: $PRETTY_NAME"
        echo "ID: $ID"
        echo "版本: $VERSION_ID"
    elif [ -f /etc/redhat-release ]; then
        echo "操作系统: $(cat /etc/redhat-release)"
    fi
    echo "内核版本: $(uname -r)"
    echo "已运行时间: $(uptime -p | sed 's/up //')"
    echo "当前用户: $(whoami)"
    echo ""
    # 硬件信息
    echo "CPU: $(lscpu | grep 'Model name' | cut -d':' -f2 | xargs)"
    echo "CPU核心数: $(nproc)"
    echo "内存: $(free -h | awk '/Mem/{print $2}') 总内存 | $(free -h | awk '/Mem/{print $3}') 已用"
    echo "交换空间: $(free -h | awk '/Swap/{print $2}') 总大小 | $(free -h | awk '/Swap/{print $3}') 已用"
    echo "系统负载: $(uptime | awk -F'load average: ' '{print $2}')"
    echo ""
    # 网络信息
    echo "IP地址: $(hostname -I | awk '{print $1}')"
    echo "公共IP: $(curl -s ifconfig.me || echo "无法获取")"
    echo ""
    # 磁盘信息
    echo "磁盘使用情况:"
    df -h | grep -v "tmpfs" | grep -v "udev"
}
update() {
#!/bin/bash
sudo dpkg --configure -a
# 检查是否以 root 运行
if [ "$(id -u)" -ne 0 ]; then
    echo "请使用 sudo 或以 root 用户运行此脚本！"
    exit 1
fi

# 获取当前发行版代号（如 jammy、focal）
CURRENT_CODENAME=$(lsb_release -cs)

# 提示用户输入新代号
read -p "当前发行版代号是 '$CURRENT_CODENAME'，请输入要更新到的版本代号（如 plucky、bookworm等）: " NEW_CODENAME

# 检查输入是否为空
if [ -z "$NEW_CODENAME" ]; then
    echo "错误：未输入新的发行版代号！"
    exit 1
fi

# 备份原文件
BACKUP_FILE="/etc/apt/sources.list.bak.$(date +%Y%m%d%H%M%S)"
cp /etc/apt/sources.list "$BACKUP_FILE"
echo "已备份原文件至 $BACKUP_FILE"
sudo apt update
# 使用 sed 替换代号
sed -i "s/$CURRENT_CODENAME/$NEW_CODENAME/g" /etc/apt/sources.list

sudo apt full-upgrade -y && \
sudo apt update && \
sudo apt autoremove -y && \
sudo apt full-upgrade -y && \
sudo apt --fix-broken install -y && \
sudo apt autoremove -y

echo "升级成功！"
}
while true; do
    clear  # 清屏
    echo "===================================="
    echo "                lic面板"
    echo "===================================="
    echo "1. 启动 x11 桌面"
    echo "2. 安装软件"
    echo "3. 创建自解压脚本"
    echo "4. 与chatgpt对话"
    echo "5. 切换语言"
    echo "6. 系统备份恢复"
    echo "7. 系统升级"
    echo "8. 查看系统信息"
    echo "9. 退出"
    echo "===================================="
    read -p "请输入数字选择 (1-9): " choice

        
    case $choice in
        1)
            sudo dpkg --configure -a
            apt-get update && sudo apt install wget -y && wget https://gitee.com/lic-miao/ubuntu-arm64/raw/master/x11.sh && bash ./x11.sh
            ;;
        2)
             read -p "请输入你想安装的包: " install
             sudo apt update
             sudo dpkg --configure -a
             sudo apt reinstall $install -y
             read -p "按 Enter 键继续..."
            ;;
        3)
             read -p "请输入要压缩的文件夹路径：" xz
             read -p "请输入解压后要启动的文件：" xf
             apt-get update && sudo apt install wget -y && wget https://gitee.com/lic-miao/ubuntu-arm64/raw/master/create_self_extractor.sh && bash create_self_extractor.sh $xz $xf
             read -p "按 Enter 键继续..."
            ;;
        4)
             chat_install
             chatgpt
             read -p "按 Enter 键继续..."
            ;;
        5)   
             echo "1.中文"
             echo "2.English"
             read -p "请选择语言：" language
             
             if [ "$language" = "1" ]
             then
                 sudo locale-gen zh_CN.UTF-8
                 sudo update-locale LANG=zh_CN.UTF-8 LC_ALL=zh_CN.UTF-8
                 sudo update-locale
                 source /etc/default/locale
                 sudo timedatectl set-timezone Asia/Shanghai
                 echo "已设置中文"
             elif [ "$language" = "2" ]
             then
                 sudo update-locale LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8
                 sudo update-locale
                 source /etc/default/locale
                 sudo timedatectl set-timezone UTC
                 echo "Language set to English"
             else
                 echo "无效输入，默认中文"
                 sudo locale-gen zh_CN.UTF-8
                 sudo update-locale LANG=zh_CN.UTF-8 LC_ALL=zh_CN.UTF-8
                 sudo update-locale
                 source /etc/default/locale
             fi
             
             read -p "按 Enter 键继续..."
            ;;
        6)
             backup
             read -p "按 Enter 键继续..."
            ;;
        7)
            update
            ;;
        8)
            system_info
            read -p "按 Enter 键继续..."
            ;;
        9)
            break
        ;;
    esac
done